<template>
  <div class="login-container">
    <form-box
      ref="registerForm"
      cancel-text="返回"
      :fields="registerItems"
      :show-btns="false"
      label-width="0"
    >
      <el-button slot="form-captcha" size="large" style="height: 46px" type="primary" :disabled="captcha.disabled" @click="sendCaptcha">{{ captcha.txt }}</el-button>
      <p v-if="errorMsg" slot="otherItems">{{ errorMsg }}</p>
    </form-box>
    <el-button class="submitBtn" :loading="submitting" type="primary" @click.native.prevent="submitHandle">提交</el-button>
    <p class="tc">
      已有账号？
      <el-link class="ml5" type="primary" @click="$router.push('/user/login')">返回登录</el-link>
    </p>
  </div>
</template>
<script>
import { sendSms, forgetPassword } from '@/api/user'
import omit from 'lodash/omit'
import { registerItems } from './config'

export default {
  name: 'Register',
  data () {
    return {
      registerItems,
      captcha: {
        txt: '获取验证码',
        disabled: false
      },
      errorMsg: '',
      submitting: false
    }
  },
  methods: {
    // 提交
    async submitHandle () {
      const values = await this.$refs.registerForm.submitForm()
      console.log(values)
      if (values.confirmPassword !== values.newPassword) {
        this.errorMsg = '两次密码不一样'
        return
      }
      this.submitting = true
      forgetPassword(omit(values, ['captcha', 'confirmPassword'])).then(res => {
        console.log(res)
        if (res) {
          this.$message.success('保存成功')
        }
      }).finally(() => {
        this.submitting = false
      })
    },
    // 验证码计时
    async sendCaptcha () {
      const that = this
      const sendFlag = await this.reqCaptcha()
      if (sendFlag) {
        let count = 59
        this.captcha.disabled = true
        const interval = setInterval(() => {
          count -= 1
          that.captcha.txt = `${count}秒后重新发送`
          if (count === 0) {
            that.captcha.txt = '重新发送'
            that.captcha.disabled = false
            interval && clearInterval(interval)
          }
        }, 1000)
      }
    },
    // 发送验证码
    async reqCaptcha () {
      console.log(this.$refs.registerForm)
      const phone = this.$refs.registerForm.formData.phone
      if (!phone) {
        this.$message.error('请输入手机号码')
        return
      }
      const data = sendSms({ phone })
      console.log(data)
      return data
    }
  }
}
</script>
<style lang="scss" scoped>
.submitBtn{
  width:100% !important;
  margin: 22px 0 30px;
}
</style>
